'''
Created on 26/03/2009

@author: eh01
'''
from im import imconfig
import datetime
import threading

class DSStub(object):
    '''
    Temporary Stub Class to stub out the responsibilities of the DataStore
    '''

    __outstanding_requests = None
    __messages = None
    __nodes = None
    __imcfg = None
    __message_sequence = 0
    __http_server_port = None
    __node_id = None
    
    def __init__(self):
        '''
        Constructor
        '''
        if self.__outstanding_requests is None:
            self.__outstanding_requests = {}
        if self.__messages is None:
            self.__messages = {}
        if self.__nodes is None:
            self.__nodes = {}

    def __new__(cls, *args, **kwargs): 
        if not hasattr(cls, 'self'):
            cls.self = object.__new__(cls, *args, **kwargs)
        return cls.self 
    
        
    def set_outstanding_requests(self, message_id, http_request):
        self.__outstanding_requests[message_id] = http_request
    
    def get_outstanding_requests(self, message_id):   
        try:
            result = self.__outstanding_requests[message_id]
            del self.__outstanding_requests[message_id]
            return result
        except KeyError:
            return None
    
    def get_node_name_by_node_id(self, node_id):
        for node_name in self.__imcfg.keys():
            if node_name.startswith('node_') and self.get_node_id_by_node_name(node_name) == node_id:
                return node_name
        return None
    
    def get_node_id_by_node_name(self, node_name):
        return self.__imcfg.get(node_name)
    
    def get_hub_username(self):
        return self.__imcfg.get(imconfig.HUB_USERNAME)
    
    def get_hub_password(self):
        return self.__imcfg.get(imconfig.HUB_PASSWORD)
    
    def get_hub_base_url(self):
        return self.__imcfg.get(imconfig.HUB_BASE_URL)
    
    def get_node_id(self):
        try:
            return self.__imcfg.get(imconfig.NODE_ID)
        except KeyError:
            return None
    
    def get_spear_host_id(self):
        return self.__imcfg.get(imconfig.SPEAR_HOST_ID)

    def get_spear_host_password(self):
        return self.__imcfg.get(imconfig.SPEAR_HOST_PASSWORD)

    def get_ca_cert(self):
        return self.__imcfg.get(imconfig.CA_CERT)
    
    def get_client_cert(self):
        return self.__imcfg.get(imconfig.CLIENT_CERT)
    
    def get_client_cert_password(self):
        return self.__imcfg.get(imconfig.CLIENT_CERT_PASSWORD)    
    
    def get_http_server_port(self):
        return int(self.__imcfg.get(imconfig.HTTP_SERVER_PORT))
        
    def get_spear_a2a_base_url(self):
        return self.__imcfg.get(imconfig.SPEAR_A2A_BASE_URL)
    
    def get_hub_wait(self):
        if self.__imcfg.get(imconfig.HUB_WAIT) == 'True':
            return True
        else:
            return False
        
    def get_number_of_event_dispatchers(self):
        return int(self.__imcfg.get(imconfig.NUMBER_OF_EVENT_DISPATCHERS))

    def add_message(self, node_id, message, message_id=None):
        # get the node messages
        node_messages = self.get_messages(node_id)
        if node_messages is None:
            node_messages = {}

        if message_id is None:
            # counter to be used as a sequence generator
            message_id = self.__message_sequence
            self.__message_sequence += 1
            
        # add message for node
        node_messages[message_id] = message
        self.__messages[node_id] = node_messages
        return message_id

    def get_message(self, node_id, message_id):
        try:
            node_messages = self.get_messages(node_id)
            if node_messages:
                message = node_messages[message_id]
                return message
            else:
                return None
        except KeyError:
            return None

    def get_messages(self, node_id):
        try:          
            node_messages = self.__messages[node_id]
            return node_messages
        except KeyError:
            return None
    
    def delete_message(self, node_id, message_id):
        node_messages = self.get_messages(node_id)
        if node_messages:
            del node_messages[message_id]
            return True
        else:
            return False
        
    def is_hub(self):
        if self.get_node_id() is None:
            return True
        else:
            return False

    def get_nodes(self):
        return self.__nodes
    
    def put_node(self, node_id):
        self.__nodes[node_id] = datetime.datetime.now()
        
    def get_currently_connected_nodes(self):
        currently_connected_nodes = {}
        for node_id in self.__nodes.keys():
            if self.is_node_currently_connected(node_id):
                currently_connected_nodes[node_id] = self.__nodes[node_id]
        return currently_connected_nodes    
    
    def is_node_currently_connected(self, node_id):
        thirty_mins = datetime.timedelta(minutes=1)
        date_time_now = datetime.datetime.now()
        date_time_thirty_mins_ago = date_time_now - thirty_mins
        try:
            timestamp = self.__nodes[node_id]
        except KeyError:
            return False
        if timestamp > date_time_thirty_mins_ago:
            return True
        else:
            return False
        
    def flush_memcache(self):
        items_flushed = 0
        items_flushed += len(self.get_nodes())
        for node_id in self.__messages.keys():
            items_flushed += len(self.get_messages(node_id).keys())
        self.__nodes = {}
        self.__messages = {}
        return items_flushed
    
    def set_IM_Config(self, imcfg):
        self.__imcfg = imcfg
        
    def is_allow_keyboard_interrupt(self):
        if self.__imcfg.get(imconfig.ALLOW_KEYBOARD_INTERRUPT) == 'True':
            return True
        else:
            return False        